<template>
  <div>
    <div v-if="isPageShow" class="wrap">
      <!-- header头部 -->
      <!-- <m-header
        :backcolor="'#1968FA'"
        :color="'#fff'"
        opacity="1"
        hocolor="#fff"
        filter="blur(0px)"
      ></m-header> -->
      <div style="height: 50px"></div>
      <div class="container" style="width: 100%; max-width: 1200px">
        <div class="content">
          <div class="right-box">
            <!-- menu栏 -->
            <m-Menu activeDefault="2"></m-Menu>
            <!--  -->
          </div>
          <div class="left-box" v-loading="$store.state.isLoading">
            <div
              style="
                position: absolute;
                top: -32px;
                display: flex;
                align-items: center;
              "
            >
              <i
                class="el-icon-back"
                style="font-size: 30px; margin-right: 10px; cursor: pointer"
                @click="$router.push('/personalcenter')"
              ></i
              >班级管理/添加班级
            </div>
            <div class="top">
              <div class="title">添加班级</div>
              <el-divider></el-divider>
              <div class="search">
                <span class="label">班级名称<span class="red">*</span></span>
                <el-input
                  style="width: 245px"
                  placeholder="请输入班级名称"
                  v-model.trim="className"
                  class="input"
                  clearable
                  @input="handleInputChange"
                >
                </el-input>
                <span v-if="isClassTrue"
                  ><span class="red"
                    ><span class="red">*</span
                    >该班级已存在，若需要添加该班次学生，请前往班级管理点击查看后添加！</span
                  ></span
                >
              </div>
              <div class="import">
                <span class="label">学生信息</span>
                <el-button
                  icon="el-icon-circle-plus"
                  type="primary"
                  plain
                  @click="handleOpenAddModifyStudent(true)"
                  >添加学生</el-button
                >
                <el-button
                  icon="el-icon-s-claim"
                  type="primary"
                  plain
                  @click="handleOpenDialog"
                  >批量导入</el-button
                >
              </div>
            </div>
            <div class="bottom">
              <el-table
                :data="tableData"
                style="width: 100%; margin-top: 30px"
                max-height="500"
                :header-cell-style="{ background: '#E4EEFF', color: '#333333' }"
              >
                <el-table-column
                  prop="name"
                  label="姓名"
                  width="180"
                  align="center"
                >
                </el-table-column>
                <el-table-column prop="mobile" label="手机号" align="center">
                </el-table-column>
                <el-table-column label="性别" align="center">
                  <template slot-scope="scope">
                    {{
                      options.find((item) => scope.row.sex == item.value).label
                    }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="280" align="center">
                  <template slot-scope="scope">
                    <span
                      style="
                        color: #1968fa;
                        cursor: pointer;
                        margin-right: 20px;
                      "
                      @click="
                        handleOpenAddModifyStudent(
                          false,
                          scope.row,
                          scope.$index
                        )
                      "
                      >编辑</span
                    >
                    <span
                      style="color: #fa1900; cursor: pointer"
                      @click="handleDelStudent(scope.$index)"
                      >刪除</span
                    >
                  </template>
                </el-table-column>
                <div slot="empty" class="empty">
                  <el-empty description="暂无数据"></el-empty>
                </div>
              </el-table>
              <div class="submit">
                <el-button
                  :disabled="isSubmit"
                  type="primary"
                  class="btn"
                  @click="handleSubmitList"
                  style="margin-bottom: 20px; background: #1968fa; color: #fff"
                  >提交</el-button
                >
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- footer页脚 -->
      <!-- <m-fotter /> -->
    </div>
    <!-- 班级批量导入弹窗 -->
    <el-dialog
      title="学生批量导入"
      :visible.sync="moreImportdialogVisible"
      width="600px"
    >
      <div class="upload-box">
        <div class="upload-tip">
          导入数据需按模版填写信息,
          <span
            @click="handleImportTemplate('学生信息表', getExcelExport)"
            style="color: #409eff; cursor: pointer"
            >点击下载</span
          >
          <!-- <em
            @click="handleImportTemplate('学生信息表', getExcelExport)"
            style="color: #409eff"
            >点击下载</em
          > -->
        </div>
        <el-upload
          class="upload-demo"
          drag
          accept
          :headers="{ Authorization: $store.state.token }"
          :action="UPLOAD_URL"
          :on-success="handleSuccessUpload"
          :show-file-list="false"
          multiple
        >
          <div v-if="excelFileUrlShow">
            <img
              src="../../assets/images/excel.png"
              style="display: block; height: 100px; margin: 30px auto 10px"
            />
            <div style="color: #409eff">{{ filedata.name }}</div>
          </div>
          <div v-else>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">仅支持Excel文件 <em>点击上传</em></div>
          </div>
        </el-upload>
      </div>
      <div
        class="input-box"
        style="display: flex; flex-direction: column; align-items: flex-start;margin-top:10px;margin-left:68px"
      >
        <div style="color: red; margin-left: 35px; font-size: 16px">
          默认密码：123456
        </div>
        <div style="color: red; margin-left: 35px; font-size: 12px;margin-top:10px">
          注：金职母婴小程序，以下网址(www.jz1x.com),如有账户会统一重置成:123456
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleImportInfo">导 入</el-button>
        <el-button @click="moreImportdialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 导入文件有误弹窗 -->
    <el-dialog
      :title="errExcelDialogTitle"
      :visible.sync="errExcelDialogVisible"
      width="500px"
    >
      <div
        v-for="item in errList"
        :key="item"
        style="padding: 10px 0px; color: red"
      >
        *{{ item }}
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="errExcelDialogVisible = false" type="primary"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 添加单个学生弹窗 -->
    <el-dialog
      :title="studentDialogTitle"
      :visible.sync="studentDialogVisible"
      width="500px"
    >
      <div class="input-box">
        <div class="dia-til"><span class="red">*</span>姓名:</div>
        <el-input
          v-model.trim="studentName"
          placeholder="请输入学生姓名"
        ></el-input>
      </div>
      <div class="input-box">
        <div class="dia-til"><span class="red">*</span>手机号:</div>
        <el-input
          v-model.trim="stuNumber"
          placeholder="请输入手机号"
        ></el-input>
      </div>
      <div class="input-box">
        <div class="dia-til"><span class="red">*</span>性别:</div>
        <el-select
          v-model="sexValue"
          clearable
          placeholder="请选择"
          style="width: 100%"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </div>
      <div class="input-box"  style="display: flex; flex-direction: column; align-items: flex-start">
        <div style="color: red; margin-left: 35px; font-size: 16px">
          默认密码：123456
        </div>
        <div style="color: red; margin-left: 35px; font-size: 12px;margin-top:10px">
          注：金职母婴小程序，以下网址(www.jz1x.com),如有账户会统一重置成:123456
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          style="margin-right: 60px"
          @click="handleAddStudent"
          >确 定</el-button
        >
        <el-button @click="studentDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { saveStu, isExistClass } from "@/api/personalCenter.js";
import { UPLOAD_URL, STATUS_CODE_OK } from "@/config";
import { getExcelExport } from "@/api/addClass.js";

import { validationMobilePhone } from "@/utils/fromcheck.js";
import { handleImportTemplate, debounce } from "@/utils/index.js";
// import MHeader from "@/components/MHeader.vue";
// import MFotter from "@/components/MFotter.vue";
import MMenu from "@/components/MMenu.vue";
export default {
  name: "saveClass",
  data() {
    return {
      isPageShow: true, //页面是否显示
      moreImportdialogVisible: false, // 批量上传弹窗显示隐藏
      excelFileUrlShow: false, //excel图标显示隐藏
      isClassTrue: false, // 班级是否已存在
      isSubmit: false, // 是否提交
      fdFlag: null, // 防抖阀
      tableData: [],
      options: [
        {
          value: "1",
          label: "男",
        },
        {
          value: "2",
          label: "女",
        },
        {
          value: "0",
          label: "保密",
        },
      ],
      filedata: {}, //上传文件数据
      handleImportTemplate,
      getExcelExport,
      errList: [], // 错误路径
      errExcelDialogVisible: false, //excel有误信息弹窗显示隐藏
      errExcelDialogTitle: "批量导入有误信息列表", //excel有误信息弹窗标题
      studentDialogTitle: "", //标题-修改/添加学生信息-弹窗
      studentDialogVisible: false, // 显示隐藏-修改/添加学生信息-弹窗
      studentName: "", //学生姓名-弹窗
      stuNumber: "", // 手机号-弹窗
      sexValue: "", // 性别
      isAdd: "", // 是否是添加
      editItem: {}, // 修改数值
      editIndex: "", // 修改index
      fileuplist: "", // 接受导入文件列表
      className: "", // 新增班级名称
      UPLOAD_URL,
      debounce,
    };
  },
  created() {
    // if (sessionStorage.getItem("classTableData")) {
    //   this.tableData = JSON.parse(sessionStorage.getItem("classTableData"));
    // }
  },
  methods: {
    //输入框失去焦点事件
    handleInputChange: debounce(function () {
      this.handleIsExistClass();
    }, 500),
    // 班级是否存在
    async handleIsExistClass() {
      let { data } = await isExistClass({
        className: this.className,
      });
      if (data.code == STATUS_CODE_OK) {
        this.isClassTrue = data.data;
        this.isSubmit = this.isClassTrue;
      }
    },
    // 批量导入学生信息
    handleImportInfo() {
      let isPipei = false;
      if (this.fileuplist.length > 0) {
        this.fileuplist.map((item) => {
          if (isPipei) {
            return false;
          }
          isPipei = this.tableData.some((sitem) => {
            return item.mobile == sitem.mobile;
          });
        });
      }
      if (isPipei) {
        this.$notify({
          title: "提示",
          message: "检测到文件中有相同手机号，请确认信息后导入!",
          type: "warning",
        });
      } else {
        if (this.fileuplist.length < 1) {
          this.$notify({
            title: "提示",
            message: "请上传.xls文件后导入!",
            type: "warning",
          });
          return;
        }
        this.fileuplist.forEach((item) => {
          this.tableData.push(item);
          this.moreImportdialogVisible = false;
          // sessionStorage.setItem(
          //   "classTableData",
          //   JSON.stringify(this.tableData)
          // );
        });
        this.$notify({
          title: "提示",
          message: "导入成功!",
          type: "success",
        });
        return;
      }
    },
    // 添加学生信息
    handleAddStudent() {
      if (!this.studentName) {
        this.$notify({
          title: "提示",
          message: "请输入姓名！",
          type: "warning",
        });
        return;
      }
      if (!this.stuNumber) {
        this.$notify({
          title: "提示",
          message: "请输入手机号！",
          type: "warning",
        });
        return;
      }
      if (!validationMobilePhone(this.stuNumber)) {
        this.$notify({
          title: "提示",
          message: "手机号格式错误！",
          type: "warning",
        });
        return;
      }
      if (!this.sexValue) {
        this.$notify({
          title: "提示",
          message: "请选择性别！",
          type: "warning",
        });
        return;
      }
      // 判断编辑新增
      if (this.isAdd) {
        // 能否添加
        let isPush = true;
        this.tableData.forEach((item) => {
          if (item.mobile === this.stuNumber) {
            isPush = false;
            this.$notify({
              title: "提示",
              message: "手机号重复，请勿录入相同手机号！",
              type: "warning",
            });
            return;
          }
        });
        if (isPush) {
          this.tableData.push({
            name: this.studentName,
            mobile: this.stuNumber,
            sex: this.sexValue,
          });
          // sessionStorage.setItem(
          //   "classTableData",
          //   JSON.stringify(this.tableData)
          // );
          this.studentDialogVisible = false;
          this.$notify({
            title: "提示",
            message: "添加成功!",
            type: "success",
          });
          return;
        }
      } else {
        this.tableData.splice(this.editIndex, 1, {
          name: this.studentName,
          mobile: this.stuNumber,
          sex: this.sexValue,
        });
        // sessionStorage.setItem(
        //   "classTableData",
        //   JSON.stringify(this.tableData)
        // );
        this.studentDialogVisible = false;
        this.$notify({
          title: "提示",
          message: "编辑成功!",
          type: "success",
        });
        return;
      }
    },

    // 删除学生信息
    handleDelStudent(item) {
      this.tableData.splice(item, 1);
      // sessionStorage.setItem("classTableData", JSON.stringify(this.tableData));
    },

    // 提交
    async handleSubmitList() {
      if (!this.className) {
        this.$notify({
          title: "提示",
          message: "请输入班级名称！",
          type: "warning",
        });
        return;
      }
      let studentlist = JSON.parse(JSON.stringify(this.tableData));
      studentlist.forEach((item) => {
        item.sex = this.options.find((fitem) => fitem.value == item.sex).value;
      });

      let datalsit = {
        classname: this.className,
        studentVOList: studentlist,
      };
      let { data } = await saveStu(datalsit);
      if (data.code == STATUS_CODE_OK) {
        this.$notify({
          title: "成功",
          message: "创建班级成功!",
          type: "success",
        });
        this.className = "";
        this.tableData = [];
        this.studentDialogVisible = false;
        this.$router.push("/personalcenter");
        // sessionStorage.clear("classTableData");
      }
    },
    // 上传成功之后
    async handleSuccessUpload(res, file) {
      if (res.code == STATUS_CODE_OK) {
        this.$notify({
          title: "成功",
          message: "上传成功!",
          type: "success",
        });
        this.filedata = file;
        this.fileuplist = res.data;
        this.excelFileUrlShow = true;
      }
      if (res.msg == "导入内容错误") {
        this.errExcelDialogVisible = true;
        this.errList = res.data;
        return;
      }
      if (res.code == -1) {
        this.$notify({
          title: "提示",
          message: res.msg,
          type: "warning",
        });
        this.excelFileUrlShow = false;
        return;
      }
    },
    // 文件上传之前
    // beforeUploadFile(file) {
    //   let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
    //   // let size = file.size / 1024 / 1024;
    //   // && extension != "xlsx"
    //   if (extension != "xls") {
    //     this.$message.warning("只能上传后缀是.xls的文件");
    //     return;
    //   }
    // },

    // 打开添加/编辑学生弹窗
    handleOpenAddModifyStudent(isAdd, item = {}, index = "") {
      // isAdd true为添加 false为修改
      this.isAdd = isAdd;
      this.editItem = item;
      this.editIndex = index;
      if (isAdd) {
        this.studentDialogTitle = "添加学生信息";
        this.studentName = "";
        this.stuNumber = "";
        this.sexValue = "";
      } else {
        this.studentDialogTitle = "修改学生信息";
        this.studentName = item.name;
        this.stuNumber = item.mobile;
        this.sexValue = item.sex;
      }
      this.studentDialogVisible = true;
    },
    handleOpenDialog() {
      this.excelFileUrlShow = false;
      this.moreImportdialogVisible = true;
    },
  },
  components: {
    // MHeader,
    // MFotter,
    MMenu,
  },
};
</script>

<style scoped lang="scss">
$bg-color: #fff;
::v-deep .el-divider--horizontal {
  margin: 20px 0;
}
::v-deep .el-dialog__footer {
  display: flex;
  justify-content: space-evenly;
}
::v-deep .el-dialog__body {
  padding: 20px;
}
::v-deep .el-menu {
  min-height: 600px;
}
.empty {
  display: flex;
  padding: 30px;
  height: 300px;
  flex-direction: column;
  justify-content: space-evenly;
  align-items: center;
  img {
    width: 250px;
    height: 250px;
  }
}
.input {
  width: 220px;
  margin-right: 20px;
}
.input-box {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
}
.dia-til {
  width: 80px;
  text-align: right;
  margin-right: 10px;
  .red {
    color: red;
    margin-right: 5px;
  }
}
.upload-box {
  .upload-tip {
    margin-left: -130px;
    margin-bottom: 20px;
  }
  display: flex;
  flex-direction: column;
  align-items: center;
}
.dialog-box {
  .pdf-box {
    overflow-y: auto;
    max-height: 600px;
    display: flex;
    width: 600px;
    flex-direction: column;
    align-items: center;
    .pdf {
      width: 100%;
      border: 1px solid #000;
      margin-bottom: 10px;
    }
  }
  .dialog-video {
    display: flex;
    align-items: center;
    justify-content: space-evenly;
  }
}
.wrap {
  background-color: $bg-color;
  .container {
    padding-bottom: 60px;
    .content {
      margin-top: 30px;
      display: flex;
      justify-content: space-between;
      .right-box {
        flex: 0.2;
        background: #fff;
        border-radius: 10px 10px 10px 10px;
        .el-menu {
          border-right: none;
        }
      }
      .left-box {
        flex: 0.8;
        position: relative;
        margin: 36px 0px 0px 20px;
        padding: 0px 20px;
        box-sizing: border-box;
        background: #fff;
        border-radius: 10px 10px 10px 10px;
        .top {
          .input {
            width: 220px;
          }
          .red {
            color: red;
            margin-left: 5px;
          }
          .search {
            .label {
              margin-right: 20px;
              .red {
                color: red;
                margin-left: 5px;
              }
            }
          }
          .import {
            margin-top: 20px;
            .label {
              margin-right: 20px;
              .red {
                color: red;
                margin-left: 5px;
              }
            }
          }
          .title {
            padding-top: 20px;
            font-size: 18px;
          }
        }
        .bottom {
          .empty {
            padding: 50px;
            height: 300px;
            .text {
              color: red;
              cursor: pointer;
            }
          }
          .submit {
            width: 100%;
            display: flex;
            justify-content: space-evenly;
            .btn {
              width: 220px;
              margin-top: 20px;
            }
          }
        }
      }
    }
  }
}
</style>
